Efficiently Calculating Legendre Symbols
The following note describes an algorithm for computing Legendre symbols in a relatively efficient way. Note that because this requires integer factorisation, the method is not fast for very large numbers. Also note that these assume that we are working modulo a prime.
Illustrative Example
Calculate
We first verify that
Now we can take out any even powers of any term, since these are trivially quadratic residues, in this case we just have
Now, we can explicitly evaluate the Legendre symbol of
For all the odd primes, we apply the law of quadratic reciprocity to flip these symbols. Note that
Then we reduce all the numerators modulo the denominators, which is valid since we are working in the same residue class.
and we are effectively back where we started, in the sense that each of these symbols can be evaluated using the method described here from top to bottom. That is, we explicitly evaluate the symbol of
It is however worth mentioning that at any point, if it is desired to work with negative numerators within the same residue class, we can pull out a
Generalised Results
This is an attempt to generalise the above, however the example above is chosen to include all of the possible useful results below, and hence is a better illustration of the process.
To compute a Legendre symbol of
If
modulo , output .
\left(\frac{0}{p}\right) = 0
If
is greater than , reduce modulo .
\left(\frac{a}{p}\right) = \left(\frac{a \mod p}{p}\right)
If
is a composite number, factorise into a product of prime powers, explicitly extracting any even powers which have Legendre symbol of .
- If
is an odd prime, apply the quadratic law of reciprocity to flip the symbol. - If
, explicitly calculate the Legendre symbol using this result.
At any point, if it is easier to work with a negative numerator in the same residue class modulo
For each Legendre symbol that is remaining after applying a step in the above process, recursively apply this algorithm on each of these symbols.